#include "screens.h"


//Screen
void Screen::setResolution(QString res){
    QStringList size = res.split("x",QString::SkipEmptyParts);

    for (int i=0; i<resolutions.size();i++){
        if(resolutions[i] == QSize(size[0].toInt(),size[1].toInt())){
            res = i;
        }
    }
}
QRectF Screen::boundingRect() const {
    return QRectF(x(),y(),resolutions[res].width(),resolutions[res].height());
}

void Screen::paint(QPainter *painter, 
        const QStyleOptionGraphicsItem *option, QWidget *widget){
    Q_UNUSED(option);
    Q_UNUSED(widget);
    painter->save();
    painter->setBrush(QColor(0,0,255,125));
    painter->drawRoundedRect(x(),y(),width(),height(),5,5);
    painter->setPen(Qt::white);
    painter->setFont(QFont("Arial", 50));
    painter->drawText(boundingRect(), Qt::AlignCenter, 
        QString("%1\n%2x%3").arg(m_id).arg(width()).arg(height()));
    painter->restore();
}

//void Screen::mouseReleaseEvent ( QGraphicsSceneMouseEvent * event ){
//    if(QGraphicsItem::x() < 0){
//        setPos(0,QGraphicsItem::y());
//    }
//    //setPos(m_x,m_y);
//
//}
        
void Screen::wheelEvent( QGraphicsSceneWheelEvent * event ){
    //QGraphicsItem::wheelEvent(event);
    //x(scenePos().x());
    //y(scenePos().y());
    if (event->delta() < 0 && res < resolutions.size() - 1){
        res++;
    }else if (event->delta() > 0 && res > 0){
        res--;
    }
    update();
}

//Setup
Setup::Setup(QString id, int width, int height) : 
    m_id(id)
    , m_width(width)
    , m_height(height)
    , m_scene(NULL)
    {
    QStringList ids = m_id.split("#",QString::SkipEmptyParts);
    foreach(QString screenId, ids){
        QStringList tokens = screenId.split(":",QString::SkipEmptyParts);
        Screen * screen = new Screen(tokens[0]);
        if(tokens.size() > 1){
            QStringList resolutions = tokens[1].split("-");
            foreach(QString resolution, resolutions){
                QStringList size = resolution.split("x");
                screen->addResolution(size[0].toInt(), size[1].toInt());
            }
        }
        else{
                screen->addResolution(0,0);
        }
        screens.insert(tokens[0],screen);
    }
}

Setup::~Setup(){
    foreach(Screen *screen, screens){
        if (m_scene) m_scene->removeItem(screen);
        delete screen;
    }
}

void Setup::loadSetup(QString cfg){
    if (cfg == "") return;

    QStringList xrandr = cfg.split(QRegExp("\\s+"),QString::SkipEmptyParts);

    QStringListIterator part(xrandr);
    QString id = "";
    part.next();
    while(part.hasNext()){
        QString command = part.next();
        if(command == "--output"){
            id = part.next();
        }
        if(command == "--mode"){
            screens[id]->setResolution(part.next());
        }
        if(command == "--pos"){
            QStringList pos = part.next().split("x");
            int x = pos[0].toInt()<0?0:pos[0].toInt(); 
            int y = pos[1].toInt()<0?0:pos[1].toInt(); 
            int maxW = m_width-screens[id]->width(); 
            int maxH = m_height-screens[id]->height(); 
            x = x>maxW?maxW:x; 
            y = y>maxH?maxH:y; 
            screens[id]->setPos(x,y);
        }
    }
}

QString Setup::bestSetup(){
    int maxW = 0;
    int maxH = 0;
    QString setup = "xrandr";
    foreach(Screen *screen, screens){
        maxW += screen->width();
        maxH += screen->height();
    }
    //Preference to horizontal setups
    if (maxW <= m_width){
        orientation = Horizontal;
        if (screens.size() == 2){
            QHash<QString,Screen *>::Iterator screen = screens.begin();
            int w = screen.value()->width();
            screen++;
            screen.value()->setPos(w,0);
         //screens[1]->x(screens[0]->width());
        }
    }
    else if (maxH <= m_height){
        orientation = Vertical;
        if (screens.size() == 2){
            QHash<QString,Screen *>::Iterator screen = screens.begin();
            int h = screen.value()->height();
            screen++;
            screen.value()->setPos(0,h);
        //    screens[1]->y(screens[0]->height());
        }
    }
    else{
        qDebug() << "Change Virtual Size";
    }
    foreach(Screen *screen, screens){
        setup += " --output " + screen->id();
        if (screen->width() > 0){
            setup +=QString(" --mode %1x%2").arg(screen->width()).arg(screen->height());
            setup +=QString(" --pos %1x%2").arg(screen->x()).arg(screen->y());
        }else{
            setup += " --off ";
        }

    }

    return setup;
}

QString Setup::setup(){
    QString setup = "xrandr";
    foreach(Screen *screen, screens){
        setup += " --output " + screen->id();
        if (screen->width() > 0){
            setup +=QString(" --mode %1x%2").arg(screen->width()).arg(screen->height());
            setup +=QString(" --pos %1x%2").arg(floor(screen->scenePos().x())).arg(floor(screen->scenePos().y()));
        }else{
            setup += " --off ";
        }
    }    
    return setup;
}

void Setup::draw(QGraphicsScene *scene){
    scene->addRect(0,0,m_width,m_height,QPen(Qt::black),QBrush(Qt::green))->setZValue(-1);
    scene->addText(QString("Virtual Desktop: %1x%2").arg(m_width).arg(m_height),QFont("Arial", 50));
    foreach(Screen *screen, screens){
        screen->setFlag(QGraphicsItem::ItemIsMovable);
        scene->addItem(screen);
    }
    m_scene = scene;
}
